//
//  PlotListViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 31/03/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "HomeViewController.h"
#import "PlantSet.h"
#import "PlantsHomeViewController.h"
#import "AppDelegate.h"
#import "Plant.h"
#import "Plot.h"
#import "ViewPlantSetTableViewController.h"
#import "BedsListTableViewController.h"
#import "UITableView+TableSectionHeaderText.h"
#import "UILabel+TextFont.h"
#import "UITableViewCell+TextFont.h"

@interface HomeViewController() 
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) NSArray *plots;
@property (nonatomic, strong) NSArray *plantSets;
@end

@implementation HomeViewController

@synthesize context = _context;
@synthesize noPlotsCell = _noPlotsCell;
@synthesize noSetsCell = _noSetsCell;
@synthesize plots = _plots;
@synthesize plantSets = _plantSets;

/*Load all the plots*/
- (void)searchPlots {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Plot"];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sorter];
    NSError *error;
    self.plots = [self.context executeFetchRequest:request error:&error];
}

/*Load all the planting sets*/
- (void)searchPlantSets {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PlantSet"];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sorter];
    NSError *error;
    self.plantSets = [self.context executeFetchRequest:request error:&error];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Grab the managedObjectContext from the AppDelegate
    self.context = [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext];
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bckgd.png"]];
    [tempImageView setFrame:self.tableView.frame]; 
    self.tableView.backgroundView = tempImageView;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self setNoSetsCell:nil];
    [self setNoPlotsCell:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self searchPlots];
    [self searchPlantSets];
    //Reload the table data each time the view appears to handle any updates to plots and planting sets
    [self.tableView reloadData];
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source


- (UITableViewCell *)buildCellsForPlots:(UITableView *)tableView withIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    static NSString *CellIdentifier;
    
    //If we have no plots, then we load up the cell telling the user to add a plot
    if([self.plots count] == 0){
        CellIdentifier = @"noPlotsCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [[NSBundle mainBundle] loadNibNamed:@"NoPlotsCell" owner:self options:nil];
            cell = _noPlotsCell;
            self.noPlotsCell = nil;
        }
        UILabel *titleLabel = (UILabel *)[cell viewWithTag:1];
        [titleLabel setSketchBlockFont];
        
        UILabel *detailLabel = (UILabel *)[cell viewWithTag:2];
        [detailLabel setMVBoliFont];
        
        UIButton *button = (UIButton *)[cell viewWithTag:3];
        [button.titleLabel setSketchBlockFont];
        button.titleLabel.textColor = [UIColor whiteColor];
        [button setBackgroundImage:[[UIImage imageNamed:@"green_button.png"]
                                    stretchableImageWithLeftCapWidth:8.0f
                                    topCapHeight:0.0f]
                          forState:UIControlStateNormal];        
    
        
        [cell setOpaque:NO];
        cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:.9];
        
        return cell;
    }
    
    CellIdentifier = @"plotCell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    Plot *plot = [self.plots objectAtIndex:indexPath.row];
    cell.textLabel.text = plot.name;
    [cell setSketchBlockFont];
    
    return cell;
}

- (UITableViewCell *)buildCellsForSets:(UITableView *)tableView withIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    static NSString *CellIdentifier;
    
    //If we have no planting sets, then we load up the cell telling the user find plants and companions
    if([self.plantSets count] == 0){
        CellIdentifier = @"noSetsCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [[NSBundle mainBundle] loadNibNamed:@"NoSetsCell" owner:self options:nil];
            cell = _noSetsCell;
            self.noSetsCell = nil;
        }
        UILabel *titleLabel = (UILabel *)[cell viewWithTag:3];
        [titleLabel setSketchBlockFont];
        
        UILabel *detailLabel = (UILabel *)[cell viewWithTag:1];
        [detailLabel setMVBoliFont];
        
        UIButton *button = (UIButton *)[cell viewWithTag:4];
        [button.titleLabel setSketchBlockFont];
        button.titleLabel.textColor = [UIColor whiteColor];
    
        
        [button setBackgroundImage:[[UIImage imageNamed:@"green_button.png"]
                                          stretchableImageWithLeftCapWidth:8.0f
                                    topCapHeight:0.0f]
                                    forState:UIControlStateNormal];        
        [cell setOpaque:NO];
        cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:.9];
        

        return cell;
    }
    
    CellIdentifier = @"textWithBugCell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    PlantSet *plantSet = [self.plantSets objectAtIndex:indexPath.row];
    
    UILabel *label = (UILabel *)[cell viewWithTag:1];
    label.text = plantSet.name;
    [label setSketchBlockFont];
    
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if(indexPath.section == 0){
        cell = [self buildCellsForPlots:tableView withIndexPath:indexPath];
    }else if(indexPath.section == 1){
        cell = [self buildCellsForSets:tableView withIndexPath:indexPath];
    }    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //ADD IN A CHECK FOR SETLIST COUNT EQUAL ZERO
    if(indexPath.section == 0 && [self.plots count] == 0){
        return 131;
    }else if(indexPath.section == 1 && [self.plantSets count] == 0){
        return 131;
    }  
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //If we have no results for the search we still return 1 because we want to be able to show a 
    //cell to tellthe user to add items to the list.
    if (section == 0) {
        if([self.plots count] == 0){
            return 1;
        }
        return [self.plots count];
    } else if (section == 1) {
        if([self.plantSets count] == 0){
            return 1;
        }
        return [self.plantSets count];
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section ==0){
        if([self.plots count]== 0){
            return;
        }
        Plot *selectedPlot = [self.plots objectAtIndex:indexPath.row];
        [self performSegueWithIdentifier:@"viewPlotSegue" sender:selectedPlot];
    }else if(indexPath.section == 1){
        if([self.plantSets count] == 0){
            return;
        }
        PlantSet *selectedSet = [self.plantSets objectAtIndex:indexPath.row];
        [self performSegueWithIdentifier:@"viewPlantSetSegue" sender:selectedSet];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"viewPlantSetSegue"]){
        [segue.destinationViewController setPlantSet:sender];
    }else if([segue.identifier isEqualToString:@"viewPlotSegue"]){
        [segue.destinationViewController setPlot:sender];
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"Your Plots";
    } else if (section == 1) {
        return @"Your Planting Sets";
    }
    return nil;
}

//This is the scroll index titles. We dont want this displayed.
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:section]; 
    return [UITableView createSectionHeaderTextLabel:sectionTitle];
}



- (IBAction)findPlantsButtonPressed:(UIButton *)sender 
{
    //Select the plants tabbar item
    self.tabBarController.selectedIndex = 2;
    
    //Set the plant finder home as the selected view
    UINavigationController *navController = (UINavigationController *) self.tabBarController.selectedViewController;
    [navController popToRootViewControllerAnimated:NO];
   
}

- (IBAction)createPlotButtonPressed:(id)sender 
{
    [self performSegueWithIdentifier:@"createPlotSegue" sender:sender];
}
@end
